package com.fengke.portal.action;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.fengke.service.vo.PageBean;
import com.fengke.util.Constants;
import com.fengke.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Description:
 * @author: BlackFalcon
 *
 */
public class BaseAction extends ActionSupport {
	private static final long serialVersionUID = -4126800070113166390L;

	private String errorMsg;
	
	private String backURL;
	
	private PageBean pageBean = new PageBean();
	/**
	 * 参数
	 */
	private Map<String, Object> value = new HashMap<String, Object>();

	/**
	 * 获得当前应用的HttpServletRequest
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得当前应用的HttpServletResponse
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获得当前应用的HttpSession
	 * @param isCreate:如果session不存在是否创建
	 */
	public HttpSession getSession(boolean isCreate) {
		HttpSession session = ServletActionContext.getRequest().getSession(isCreate);
		if (session == null) {
			return null;
		} else {
			return session;
		}
	}
	
	/**
	 * 删除session中的某个属性
	 */
	public void removeSessionAttr(String attrName) {
		HttpSession session = getSession(false);
		if(session != null) {
			session.removeAttribute(attrName);
		}
	}

	/**
	 * 从Request的Attribute中获取值
	 * @param key
	 * @return Object
	 */
	public Object getRequestAttr(String key) {
		return ServletActionContext.getRequest().getAttribute(key);
	}
	
	/**
	 * 从Request的parameter中获取值
	 * @param key
	 * @return Object
	 */
	public String getParameterAttr(String key) {
		return ServletActionContext.getRequest().getParameter(key);
	}

	/**
	 * 给Request的Attribute中赋值
	 * @param key
	 * @param value
	 */
	public void setRequestAttr(String key, Object value) {
		ServletActionContext.getRequest().setAttribute(key, value);
	}

	/**
	 * 从SESSION中获得值
	 * @param key
	 * @return Object
	 */
	public Object getSessionAttr(String key) {
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		if (session == null) {
			return null;
		} else {
			return session.getAttribute(key);
		}
	}

	/**
	 * 给session赋值
	 * @param key
	 * @param value
	 */
	public void setSessionAttr(String key, Object value) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute(key, value);
	}

	/**
	 * 获得访问者IP
	 * @return String
	 */
	public String getRemoteIp() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return getRealIp(ip);

	}

	/**
	 * 获得去除代理的IP地址
	 * @param ip
	 * @return
	 */
	public String getRealIp(String ip) {
		String realIps[] = this.splitStr(ip, ",");
		for (int i = 0; i < realIps.length; i++) {
			if(!realIps[i].equalsIgnoreCase("unknown")){
				return realIps[i];
			}
		}
		return ip;
	}
	/**
	 * 根据传入的分割符分割数组
	 * @param str
	 * @return
	 */
	private String[] splitStr(String str, String split) {
		StringTokenizer commaToker = new StringTokenizer(str, split);
		String[] strs = new String[commaToker.countTokens()];
		int i = 0;
		while (commaToker.hasMoreTokens()) {
			strs[i] = commaToker.nextToken();
			i++;
		}
		return strs;
	}
	/**
	 * 获得访问者PORT
	 * @return int
	 */
	public int getRemotePort() {
		return ServletActionContext.getRequest().getRemotePort();
	}

	/**
	 * 获得访问者URL
	 * @return String
	 */
	public String getRequestURL() {
		StringBuilder url = new StringBuilder();
		if (null != this.getRequest().getQueryString()) {
			url.append(ServletActionContext.getRequest().getRequestURL()).append("?").append(
					this.getRequest().getQueryString());
		} else {
			url.append(ServletActionContext.getRequest().getRequestURL());
		}
		return url.toString();
	}

	/**
	 * 获得访问者浏览器
	 * @return String
	 */
	public String getRequestBrowser() {
		String userAgent = getRequestUserAgent();
		String[] agents = userAgent.split(";");
		if (agents.length > 1) {
			return agents[1].trim();
		} else {
			return null;
		}
	}

	/**
	 * 获得访问者操作系统
	 * @return String
	 */
	public String getRequestOs() {
		String userAgent = getRequestUserAgent();
		String[] agents = userAgent.split(";");
		if (agents.length > 2) {
			return agents[2].trim();
		} else {
			return null;
		}
	}

	/**
	 * 获得访问者的代理全部信息
	 * @return String
	 */
	public String getRequestUserAgent() {
		HttpServletRequest req = ServletActionContext.getRequest();
		String userAgent = req.getHeader("user-agent");
		return userAgent;
	}

	/**
	 * 添加cookie
	 * @param cookie
	 */
	public void addCookie(Cookie cookie) {
		ServletActionContext.getResponse().addCookie(cookie);
	}

	/**
	 * 获取cookie
	 * @param name
	 * @return Cookie
	 */
	public Cookie getCookie(String name) {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(name)) {
					return cookies[i];
				}
			}
		}
		return null;
	}
	
	
	public HashMap<String,String> getParamMap(){
		HashMap<String,String> resMap = new HashMap<String,String>();
		HttpServletRequest request = this.getRequest();
		@SuppressWarnings("rawtypes")
		Enumeration ee =request.getParameterNames();
		while(ee.hasMoreElements()){
			String name = (String)ee.nextElement();
			String value =(String)request.getParameter(name);
			resMap.put(name, value);
		}
		return resMap;
	}
	
	public static void main(String[] args) {
		
//		try {
//			System.out.println(java.net.URLDecoder.decode("http://10.12.11.38:7001/system/zzzdinterface?cmd=10&txt_username=boss&type=1&url=10.12.11.38:7001/system/zzzd/song.jsp&zzkpzddata=01%A1%F801%A1%F8+%B9%F9%CE%B0%B5%74%D5%C5%D3%F1%AC%42%A1%F83000.00%A1%F82005-08-26%A1%F8boss%A1%F89876543210%A1%F8%A1%F845%A1%F820050701-20050831%D3%A6%B8%B6%A3%BA48.44%CA%B5%B8%B6%A3%BA48.00%CA%FD%BE%DD%D2%B5%CE%F1%B7%D1%BA%AC%B6%CC%D0%C5%B7%D1%A3%AC%B3%A4%CD%BE%CD%A8%BB%B0%B7%D1%BA%AC%B9%FA%C4%DA%C2%FE%D3%CE%A1%F8%28+50%D4%AA%29%B3%E4%D6%B5%BF%A8%40%4082%40%40%D5%C5%40%4010%40%40100.00%40%401000.00%23%23%B4%A2%D6%B5%BF%A8%40%4042%40%40%D5%C5%40%4010%40%40100.00%40%401000.00%23%23%BC%C7%D5%CB%BF%A8%40%40176%40%40%D5%C5%40%4010%40%40100.00%40%401000.00%23%23%A1%F80016EC713C43%A1%F47652be22","GBK"));
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		StringBuffer a = new StringBuffer("a");
		StringBuffer b = new StringBuffer("b");
		operate(a, b);
		System.out.println(a + ", " + b);
		
		try {
			return ;
		} finally {
			System.out.println("Finally");
		}
		
	}

	private static void operate(StringBuffer x, StringBuffer y) {
		x.append(y);
		y = x;
		
	}
	/**
	 * 页面成功提示信息
	 * 
	 * @param successMessage
	 */
	public void addPageSuccessMessage(String successMessage) {
		this.addPageMessage(Constants.PageMessage.SUCCESS, successMessage);
	}

	/**
	 * 页面错误提示信息
	 * 
	 * @param dangerMessage
	 */
	public void addPageDangerMessage(String dangerMessage) {
		this.addPageMessage(Constants.PageMessage.DANGER, dangerMessage);
	}
	/**
	 * 页面警告提示信息
	 * 
	 * @param warningMessage
	 */
	public void addPageWarningMessage(String warningMessage) {
		this.addPageMessage(Constants.PageMessage.WARNING, warningMessage);
	}
	/**
	 * 页面 信息 提示信息
	 * 
	 * @param infoMessage
	 */
	public void addPageInfoMessage(String infoMessage) {
		this.addPageMessage(Constants.PageMessage.INFO, infoMessage);
	}
	/**
	 * 设置页面提示信息
	 * 
	 * @param pageAttrName
	 * @param message
	 */
	private void addPageMessage(String pageAttrName, String message) {
		String pageAttrValue = (String) this.getRequestAttr(pageAttrName);
		if(!StringUtil.isEmpty(pageAttrValue)) {
			this.setRequestAttr(pageAttrName, pageAttrValue + "<br/>" + message);
		} else {
			this.setRequestAttr(pageAttrName, message);
		}
	}
	/**
	 * 检查是否有错误信息
	 * 
	 * @return
	 */
	public boolean hasPageDangerMessage() {
		String pageAttrValue = (String) this.getRequestAttr(Constants.PageMessage.DANGER);
		if(StringUtil.isEmpty(pageAttrValue)) {
			return false;
		}
		return true;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public Map<String, Object> getValue() {
		return value;
	}

	public void setValue(Map<String, Object> value) {
		this.value = value;
	}

	public String getBackURL() {
		return backURL;
	}

	public void setBackURL(String backURL) {
		this.backURL = backURL;
	}
}
